package org.dromara.easyes.core.service.impl;

import org.dromara.easyes.common.utils.Assert;
import org.dromara.easyes.common.utils.ReflectionKit;
import org.dromara.easyes.common.utils.StringUtils;
import org.dromara.easyes.core.biz.EntityInfo;
import org.dromara.easyes.core.core.BaseEsMapper;
import org.dromara.easyes.core.service.IService;
import org.dromara.easyes.core.toolkit.EntityInfoHelper;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 由 Easy-Es 提供的顶级增强 Service 接口的默认实现类。
 *
 * @param <M> 映射类（Mapper）类型
 * @param <T> 实体类（Entity）类型
 * @author 王帅
 * @since 2.0.0
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public class ServiceImpl<M extends BaseEsMapper<T>, T> implements IService<T> {

    @Autowired
    protected M baseMapper;

    @Override
    public BaseEsMapper<T> getBaseMapper() {
        return baseMapper;
    }

    @Override
    public boolean saveOrUpdate(T entity) {
        if (entity != null) {
            EntityInfo entityInfo = EntityInfoHelper.getEntityInfo(entity.getClass());
            Assert.notNull(entityInfo, "Can not execute. because can not find cache of EntityInfo for entity!");
            Field keyField = entityInfo.getKeyField();
            Assert.notNull(keyField, "Can not execute. because can not find column for id from entity!");
            Object idVal = ReflectionKit.getFieldValue(keyField, entity);
            return StringUtils.checkValNull(idVal) || Objects.isNull(getById((Serializable) idVal)) ? save(entity) : updateById(entity);
        }
        return false;
    }

}